import services from '../../services/api';
const initialState = {
  menu: [],
  asideHighlight: [],
  collapsed: false,
  count: 0,
};
export default {
  name: 'menu',
  state: initialState,
  reducers: {
    updateMenu: (state, { data }) => {
      return {
        ...state,
        menu: data,
      };
    },
    updateCollapsed: (state, { data }) => {
      return {
        ...state,
        collapsed: data,
      };
    },
    updateAsideHighlight: (state, { ids }) => {
      return {
        ...state,
        asideHighlight: ids,
      };
    },
    updateAuditCount: (state, { count }) => {
      return {
        ...state,
        auditCount: count,
      };
    },
  },
  effects: {
    queryMenu: async ({ params }, { dispatch }) => {
      const res = await services.menu.query(params);
      if (res.code === 0) {
        // 删除空的children属性 start
        const deleteNullChildren = (menu) => {
          if (menu.children) {
            if (menu.children.length > 0) {
              menu.children.forEach((item) => {
                deleteNullChildren(item);
              });
            } else {
              delete menu.children;
            }
          }
        };
        deleteNullChildren(res.data.root);
        // 删除空的children属性 end
        dispatch({ type: 'menu/updateMenu', data: res.data.root.children });
        return res.data.root.children;
      } else {
        dispatch({ type: 'menu/updateMenu', data: [] });
        return [];
      }
    },
    pendingCount: async ({ params }, { dispatch }) => {
      const res = await services.audit.pendingCount(params);
      if (res.code === 0) {
        dispatch({ type: 'menu/updateAuditCount', count: res.data });
        return res.data;
      }
    },
  },
};
